﻿namespace PugLib.UnitTest
{
	using System;
	using System.Threading;

	using Microsoft.VisualStudio.TestTools.UnitTesting;

	[TestClass]
	public class AsyncContinuationTest
	{
		[CssIteration("vstfs:///Classification/Node/49c1bd27-b5b4-4748-8c86-1352ecbda0ff")]
		[CssProjectStructure("vstfs:///Classification/Node/8c586b06-b45b-4d14-ab22-8322108a616d")]
		[Description("Tests an APM-style wrapper of Task")]
		[TestMethod]
		public void AsyncContinuation_End_AssumedNullCallback_Succeeds()
		{
			const Int32 sleep = 5;
			AsyncContinuation<Int32, String> task = new AsyncContinuation<Int32, String>(DoWork, sleep);
			IAsyncResult beginResult = task.Begin();
			String result = task.End(beginResult);
			Assert.AreEqual("Slept for " + sleep + " seconds", result);
		}

		[CssIteration("vstfs:///Classification/Node/49c1bd27-b5b4-4748-8c86-1352ecbda0ff")]
		[CssProjectStructure("vstfs:///Classification/Node/8c586b06-b45b-4d14-ab22-8322108a616d")]
		[Description("Tests an APM-style wrapper of Task")]
		[TestMethod]
		public void AsyncContinuation_End_Succeeds()
		{
			const Int32 sleep = 5;
			AsyncContinuation<Int32, String, Object> task = new AsyncContinuation<Int32, String, Object>(DoWork, sleep, null, null);
			IAsyncResult beginResult = task.Begin();
			String result = task.End(beginResult);
			Assert.AreEqual("Slept for " + sleep + " seconds", result);
		}

		[CssIteration("vstfs:///Classification/Node/49c1bd27-b5b4-4748-8c86-1352ecbda0ff")]
		[CssProjectStructure("vstfs:///Classification/Node/8c586b06-b45b-4d14-ab22-8322108a616d")]
		[Description("Tests an APM-style wrapper of Task")]
		[TestMethod]
		public void AsyncContinuation_Continuation_Succeeds()
		{
			const Int32 sleep = 5;
			AsyncContinuation<Int32, String, Double> task = new AsyncContinuation<Int32, String, Double>(DoWork, sleep, PrintResult, 3.14);
			task.Begin();
			Thread.Sleep(TimeSpan.FromSeconds(sleep * 2));
		}

		private static void PrintResult(Double forwardedState, String result)
		{
			Assert.AreEqual(3.14, forwardedState);
			Assert.AreEqual("Slept for 5 seconds", result);
		}

		private static String DoWork(Int32 seconds)
		{
			Thread.Sleep(TimeSpan.FromSeconds(seconds));
			return "Slept for " + seconds + " seconds";
		}
	}
}